package chat

import (
	"fmt"
	"regexp"
	"shangyuapi/data_source"
	"shangyuapi/models"
	"strconv"
	"strings"
	"time"
	"unicode/utf16"
)

var (
	Clients = make(map[int64]*Client)
	//groupMsgChan  = make(chan *message, 100)
	chatMsgChan   = make(chan *message, 100)
	chatMsgxitong = make(chan *message, 100)
)

func init() {

	go forwardMessage()
}

func forwardMessage() {
	for {
		select {
		case msg, ok := <-chatMsgChan:
			if !ok {
				break
			}
			addtime := time.Now().Unix()
			messageadd := models.Message{
				Friendsid: msg.Friendsid,
				Receiveid: msg.Receiveid,
				Content:   EmojiDecode(msg.Content),
				Addtime:   addtime,
				Classify:  msg.Classify,
			}
			data_source.Db.Create(&messageadd)
			msg.ID = messageadd.ID
			msg.Addtime = addtime
			if client, ok := Clients[msg.Receiveid]; ok {
				client.Sender <- msg
			}
			if client, ok := Clients[msg.Friendsid]; ok {
				client.Sender <- msg
			}
			if msg.Classify == 4 {
				data_source.Db.Model(&models.Message{}).Where("id = ?", msg.Content).Update("classify", 4)
			} else if msg.Classify == 5 {
				data_source.Db.Model(&models.Message{}).Where("id = ?", msg.Content).Update("classify", 5)
			} else {
				// 聊天双方建立联系
				var sourceUserChat models.UserChat
				data_source.Db.
					Where("user_id = ? and chat_id = ?", msg.Receiveid, msg.Friendsid).
					First(&sourceUserChat)
				// 从未聊过
				if sourceUserChat.ID == 0 {
					data_source.Db.Create(&models.UserChat{
						UserId:    msg.Receiveid,
						ChatId:    msg.Friendsid,
						CreatedAt: addtime,
						UpdatedAt: addtime,
						Content:   EmojiDecode(msg.Content),
						Classify:  msg.Classify,
					})
				} else {
					uc := models.UserChat{
						UpdatedAt: addtime,
						Content:   EmojiDecode(msg.Content),
						Classify:  msg.Classify,
					}
					data_source.Db.Where("id = ?", sourceUserChat.ID).Updates(&uc)
				}

				var targetUserChat models.UserChat
				data_source.Db.
					Where("user_id = ? and chat_id = ?", msg.Friendsid, msg.Receiveid).
					First(&targetUserChat)
				// 从未聊过
				if targetUserChat.ID == 0 {
					data_source.Db.Create(&models.UserChat{
						UserId:    msg.Friendsid,
						ChatId:    msg.Receiveid,
						CreatedAt: addtime,
						UpdatedAt: addtime,
						Content:   EmojiDecode(msg.Content),
						Classify:  msg.Classify,
					})
				} else {
					uc := models.UserChat{
						UpdatedAt: addtime,
						Content:   EmojiDecode(msg.Content),
						Classify:  msg.Classify,
					}
					data_source.Db.Where("id = ?", targetUserChat.ID).Updates(&uc)
				}
			}

		}
	}
}

// EmojiDecode Emoji表情解码
func EmojiDecode(s string) string {
	re := regexp.MustCompile("\\\\u[ed][0-9a-f]{3}\\\\u[ed][0-9a-f]{3}")
	result := re.FindAllString(s, -1)
	if len(result) > 0 {
		for k := range result {
			tmp := result[k]
			result[k] = strings.Replace(result[k], "\\u", "0x", -1)
			cov1, _ := strconv.ParseUint(result[k][:6], 0, 32)
			cov2, _ := strconv.ParseUint(result[k][6:], 0, 32)
			covResult := fmt.Sprintf("%c", utf16.DecodeRune(rune(cov1), rune(cov2)))
			s = strings.Replace(s, tmp, covResult, -1)
		}
	}
	return s
}
